package simorg.actions;


import org.dom4j.Document;
import org.dom4j.Element;

import simorg.controller.UserController;
import simorg.domain.Role;
import simorg.domain.User;
import simorg.domain.persistence.UserTable;
import simorg.view.ModelView;
import simorg.view.Page;
import simorg.view.SessionAttribute;
import simorg.view.WebSessionContext;

public class UserView extends Action {

	public static String actionName = "view";
	public UserView() {
		super(actionName);
		this.controllerName = UserController.controllerName;
	}
	
	public UserView(String userId) {
		super(actionName);
		this.controllerName = UserController.controllerName;
		this.getRequestArgs().add(userId);
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	
	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		Document xmlDoc = this.getBaseXml(wc);
		Element userElement = xmlDoc.getRootElement().addElement( "selected-user" );
		User loggedInUser = (User) wc.getSessionAttribute(SessionAttribute.User);
		int id = Integer.parseInt(this.getRequestArgs().get(0));
		User user = UserTable.findById(wc.getDbConnection(), id);
		user.buildDomainXml(userElement);
		boolean editPassword = loggedInUser.getRole() == Role.Admin || loggedInUser.getUsername().equalsIgnoreCase(user.getUsername());
		wc.getViewOptions().put("passwordedit", String.valueOf(editPassword));
		return new ModelView(Page.User, xmlDoc);
	}

}
